<?php

declare(strict_types=1);

namespace app\controller\admin;

use app\controller\admin\AdminBaseController;
use app\model\admin\SysMember as SysMemberModel;
use app\model\admin\SysMemberGroup as SysMemberGroupModel;

use think\facade\Db;
use think\Request;

class SysMember extends AdminBaseController
{
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index(Request $request)
    {
        $field = "*";
        $data = SysMemberModel::with('group')->scope('where', $request->param())
            ->scope('dataFilter')
            ->field($field)
            ->order('id', 'desc')
            ->paginate([
                'list_rows' => $this->limit,
                'page' => $this->page,
                'var_page' => $this->pageVar
            ]);
        return successPage($data);
    }

    public function show(Request $request)
    {
        $id = $request->param('id', 0);

        $data = SysMemberModel::where('id', $id)->scope('dataFilter')->find();

        $groups = SysMemberGroupModel::scope('dataFilter')->select();
        $groups_data = $groups->toArray();
        array_unshift($groups_data, [
            'id' => 0,
            'group_name' => '无分组',
        ]);
        return success([
            'user' => $data,
            'groups' => $groups_data,
        ]);
    }


    public function save(Request $request)
    {
        $param = $request->param();

        if (isset($param['id'])) {
            unset($param['id']);
        }
        $param['password'] = md5($param['password']);
        $data = SysMemberModel::create($param);
        $user_id = $data->id;
        return $user_id ? success([], "新增成功") : error('操作失败');
    }

    public function update(Request $request)
    {
        $param = $request->except(['password', 'login_ip', 'login_time', 'create_by']);
        $id = $param['id'];
        if (isset($param['id'])) {
            unset($param['id']);
        }


        $model = SysMemberModel::where('id', $id)->scope('dataFilter')->find();

        $msg = 'success';

        $ret = $model->save($param);
        return $ret ? success([], "更新成功") : error($msg);
    }
    public function changeStatus(Request $request)
    {
        $id = $request->param('id');
        $status = $request->param('status', '');
        if (!$id || $status == '') {
            return error('缺少必要参数');
        }

        $model = SysMemberModel::where('id', $id)->scope('dataFilter')->find();

        $data = $request->only(['status']);

        $ret = $model->save($data);
        if (!$ret) {
            return error('更新失败');
        }
        return success();
    }

    public function resetPwd(Request $request)
    {
        $id = $request->post('id');
        $password = $request->post('password');


        $user = SysMemberModel::where('id', $id)->scope('dataFilter')->find();
        if (!$user) {
            return error('数据不存在');
        }
        $user->password = md5(trim($password));
        $user->save();

        return success([], '更新成功');
    }

    public function delete(Request $request)
    {
        $id = $request->param('id', '');
        if (!$id) {
            return error('缺少必要参数');
        }

        $ids = explode(',', $id);
        if (in_array(1, $ids)) {
            return error('包含不可删除数据');
        }

        Db::startTrans();
        $msg = 'success';
        try {
            $ret = SysMemberModel::destroy($ids);
            DB::table('sys_user_role')->whereIn('user_id', $ids)->delete();
            $result = true;
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            $result = false;
            $msg = $e->getMessage();
            // 回滚事务
            Db::rollback();
        }
        return $result ? success([], "删除成功") : error($msg);
    }

    public function profile(Request $request)
    {
        $id = $request->create_by;
        $data = SysMemberModel::with(['dept', 'roles'])->where('id', $id)->find();
        $roleGroup = $data->roles()->column('role_name');
        return success([
            'user' => $data,
            'roleGroup' => implode(',', $roleGroup)
        ]);
    }

    public function updateProfile(Request $request)
    {
        $id = $request->create_by;
        if (!$id) {
            return error('缺少必要参数');
        }

        $data = $request->only(['nickname', 'email', 'phone', 'sex']);
        $data['update_by'] = $id;
        $data['update_time'] = time();

        $ret = Db::table('sys_user')->where('id', $id)->update($data);

        if (!$ret) {
            return error('更新失败');
        }
        return success();
    }

    public function updatePwd(Request $request)
    {
        $id = $request->create_by;
        if (!$id) {
            return error('缺少必要参数');
        }

        $param = $request->only(['oldPassword', 'newPassword']);
        $oldPassword = $param['oldPassword'];
        $newPassword = $param['newPassword'];
        if (!$oldPassword || !$newPassword) {
            return error('缺少必要参数');
        }
        $model = SysMemberModel::find($id);
        if ($model->password != md5($oldPassword)) {
            return error('旧密码不正确');
        }

        $data = [];
        $data['update_by'] = $id;
        $data['update_time'] = time();
        $data['password'] = md5($newPassword);

        $ret = Db::table('sys_user')->where('id', $id)->update($data);

        if (!$ret) {
            return error('更新失败');
        }
        return success();
    }
}
